package com.wyth.lottery.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.printer.sdk.PrinterConstants;
import com.printer.sdk.PrinterInstance;
import com.wyth.lottery.R;
import com.wyth.lottery.base.BaseActivity;
import com.wyth.lottery.code.BitmapT;
import com.wyth.lottery.code.GlobalContants;
import com.wyth.lottery.code.PrefUtils;
import com.wyth.lottery.code.UsbDeviceList;
import com.wyth.lottery.utils.MyApplication;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by phh on 2017/11/4.
 * 支付成功  出票界面
 */

public class PayOKActivity extends BaseActivity {
    Bitmap monoChromeBitmap = null;
    public static final int CONNECT_DEVICE = 1;
    public static boolean isConnected = false;
    private static UsbDevice mUSBDevice;
    public static PrinterInstance myPrinter;
    public static String devicesName = "未知设备";
    private static final String ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION";
    protected static final String TAG = "SettingActivity";

    @BindView(R.id.relativelayout)
    RelativeLayout mRelativelayout;
    @BindView(R.id.relativelayout2)
    RelativeLayout mRelativelayout2;

    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {

        @Override
        public void run() {
            outSuccess();
        }
    };

    /**
     * 出票成功后,界面装换
     */
    private void outSuccess() {
        mRelativelayout.setVisibility(View.GONE);
        mRelativelayout2.setVisibility(View.VISIBLE);
    }

    @Override
    protected int getContentID() {
        return R.layout.activity_pay_ok;
    }

    @Override
    protected void initView() {
        mRelativelayout.setVisibility(View.VISIBLE);
        mRelativelayout2.setVisibility(View.INVISIBLE);
        monoChromeBitmap = BitmapT.bitmaptest1(activity);
    }

    @Override
    protected void initDate() {
        String payOKActivity = getIntent().getStringExtra("PayOKActivity");
        System.out.println(payOKActivity + "-------------------------------");
        Intent intent = new Intent(activity, UsbDeviceList.class);
        startActivityForResult(intent, CONNECT_DEVICE);
        handler.postDelayed(runnable, 3000);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //  handler.removeCallbacks(runnable);
    }


    @OnClick(R.id.tv_return)
    public void onViewClicked() {
        startActivity(new Intent(MyApplication.getContext(), MainActivity.class));
        finish();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK)
            return;
        if (requestCode == CONNECT_DEVICE) {// 连接设备
            mUSBDevice = data.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            myPrinter = PrinterInstance.getPrinterInstance(activity, mUSBDevice, mHandler);
            devicesName = "USB device";
            UsbManager mUsbManager = (UsbManager) activity.getSystemService(Context.USB_SERVICE);
            if (mUsbManager.hasPermission(mUSBDevice)) {
                myPrinter.openConnection();
            } else {
                // 没有权限询问用户是否授予权限
                PendingIntent pendingIntent = PendingIntent.getBroadcast(activity, 0,
                        new Intent(ACTION_USB_PERMISSION), 0);
                IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
                filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
                filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
                activity.registerReceiver(mUsbReceiver, filter);
                mUsbManager.requestPermission(mUSBDevice, pendingIntent); // 该代码执行后，系统弹出一个对话框
            }

        }
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @SuppressLint("NewApi")
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.w(TAG, "receiver action: " + action);
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    activity.unregisterReceiver(mUsbReceiver);
                    UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                            && mUSBDevice.equals(device)) {
                        myPrinter.openConnection();
                    } else {
                        mHandler.obtainMessage(PrinterConstants.Connect.FAILED).sendToTarget();
                        Log.e(TAG, "permission denied for device " + device);
                    }
                }
            }
        }
    };

    private void printBitmap() {
        if (PrinterInstance.mPrinter == null) {
            Toast.makeText(activity, getString(R.string.not_support), Toast.LENGTH_SHORT).show();
        } else {
            PrinterInstance.mPrinter.printColorImg2Gray(monoChromeBitmap, PrinterConstants.PAlign.NONE, 0, false);
            byte[] data = {0x0C, 0x1D, 0x56, 0x01};
            PrinterInstance.mPrinter.sendBytesData(data);

        }
    }

    private Handler mHandler = new Handler() {
        @SuppressLint("ShowToast")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PrinterConstants.Connect.SUCCESS:
                    isConnected = true;
                    GlobalContants.ISCONNECTED = isConnected;
                    GlobalContants.DEVICENAME = devicesName;
                    Toast.makeText(activity, "连接成功", Toast.LENGTH_SHORT).show();
                    printBitmap();
                    break;
                case PrinterConstants.Connect.FAILED:
                    isConnected = false;
                    Toast.makeText(activity, "连接失败", Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "连接失败!");
                    break;
                case PrinterConstants.Connect.CLOSED:
                    isConnected = false;
                    GlobalContants.ISCONNECTED = isConnected;
                    GlobalContants.DEVICENAME = devicesName;
                    Toast.makeText(activity, "连接关闭", Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "连接关闭!");
                    break;
                case PrinterConstants.Connect.NODEVICE:
                    isConnected = false;
                    Toast.makeText(activity, "我就不告诉你", Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    Toast.makeText(activity, "打印机通信正常!", Toast.LENGTH_SHORT).show();
                    break;
                case -1:
                    Toast.makeText(activity, "打印机通信异常常，请检查蓝牙连接!", Toast.LENGTH_SHORT).show();
                    vibrator();
                    break;
                case -2:
                    Toast.makeText(activity, "打印机缺纸!", Toast.LENGTH_SHORT).show();
                    vibrator();
                    //TODO 把未打印号码传给PrintErrorActivity
                    String noPrintNumber = "111111111111";
                    Intent intent = new Intent(PayOKActivity.this, PrintErrorActivity.class);
                    intent.putExtra("noPrintNumber", noPrintNumber);
                    startActivity(intent);
                    finish();
                    break;
                case -3:
                    Toast.makeText(activity, "打印机开盖!", Toast.LENGTH_SHORT).show();
                    vibrator();
                    break;
                default:
                    break;
            }

        }

    };
    int count = 0;

    @SuppressWarnings("static-access")
    public void vibrator() {
        count++;
        PrefUtils.setInt(activity, "count3", count);
        MediaPlayer player = new MediaPlayer().create(activity, R.raw.test);
        player.start();

    }
}
